package android.bkav.testing.utils;

import java.sql.Date;
import java.text.SimpleDateFormat;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseNoteAdapter {
	
	//Database fields
	public static final String KEY_ROWID = "_id";
	public static final String KEY_TITLE = "note_title";
	public static final String KEY_CONTENT = "note_content";
	public static final String KEY_TIME_DATE = "date_time";
	
	private static final String DATABASE_TABLE = "dbnotes";
	
	private Context context;
	private SQLiteDatabase database;
	private DatabaseNoteHelper dbHelper;
	private String strDateTime;
	
	public DatabaseNoteAdapter(Context context){
		this.setContext(context);
	}
	
	public DatabaseNoteAdapter open() throws SQLException{
		dbHelper = new DatabaseNoteHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}
	
	public void close(){
		dbHelper.close();
	}
	
	public long createDbNotes(String title, String content, long date_time){
		ContentValues initialValues = createContentValues(title, content, date_time);
		return database.insert(DATABASE_TABLE, null, initialValues);
	}
	
	//Update Database
	public boolean updateDbNotes(long rowId, String title, String content, int date_time){
		ContentValues updateValues = createContentValues(title, content, date_time);
		return database.update(DATABASE_TABLE, updateValues, KEY_ROWID + "=" + rowId, null) > 0;
	}
	
	//Delete Database
	public boolean deleteDbNotes(long rowId){
		return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}
	
	//Return a Cursor over the list of all in the database
	public Cursor fetchAllDbNotes(){
		return database.query(DATABASE_TABLE, new String[]{KEY_ROWID, KEY_TITLE, KEY_CONTENT, KEY_TIME_DATE}, null, null, null, null, null);
	}
	
	//Return a Cursor positioned at the defined DbNotes
	public Cursor fetchDbNotes(long rowId) throws SQLException{
		Cursor mCursor = database.query(true, DATABASE_TABLE, new String[]{ KEY_ROWID, KEY_TITLE, KEY_TIME_DATE}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
		if(mCursor != null){
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	public ContentValues createContentValues(String title, String content, long date_time){
		Date date = new Date(date_time);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy 'at' h:mm a");
		strDateTime = simpleDateFormat.format(date).toString();
		
		ContentValues values = new ContentValues();
		values.put(KEY_TITLE, title);
		values.put(KEY_CONTENT, content);
		values.put(KEY_TIME_DATE, strDateTime);
		return values;
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}
}
